//
//  AddBankCardVC.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/9/7.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import SVProgressHUD

class BankInfoModel: NSObject {
    var mob_phone : String?
    var bank_name : String?
    var true_name  : String?
    var bank_number  : String?
    var bank_code  : String?
    
}

class AddBankCardVC: BaseViewController {
    
    var block : (() -> ())?
    
    var model = BankInfoModel()
    
    
    
    lazy var tableView : UITableView = {
        
        let tabV = UITableViewController(style: .plain)
        
        tabV.tableView.delegate = self
        tabV.tableView.dataSource = self
        tabV.tableView.showsVerticalScrollIndicator = false
        tabV.tableView.showsHorizontalScrollIndicator = false
        tabV.tableView.allowsSelection = true
        
        tabV.tableView.frame = self.view.bounds
        
        self.view.addSubview(tabV.tableView)
        
        self.addChildViewController(tabV)
        
        
        return tabV.tableView
        
    }()
    
    
    lazy var bottomView : OrderBottomView = {
        
        let temp : OrderBottomView = Bundle.main.loadNibNamed(self.StringFromClass(classType: OrderBottomView.self), owner: nil, options: nil)?.first as! OrderBottomView
        
        temp.frame = CGRect(x: 0, y: 0, width: KScreenW, height: 118)
        
        temp.btn.setTitle("确认", for: .normal)
        
        temp.delegate = self
        
        return temp
        
    }()

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title = "添加银行卡"
        
        tableView.tableFooterView = bottomView
        
        tableView.register(UINib(nibName: StringFromClass(classType: OrderSureSetionView.self), bundle: nil), forHeaderFooterViewReuseIdentifier: OrderSureSetionView.identifer())
        
        
        
        
        tableView.register(UINib(nibName: StringFromClass(classType: BankInfoCollectionCell.self), bundle: nil), forCellReuseIdentifier: BankInfoCollectionCell.identifer())


        // Do any additional setup after loading the view.
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        SVProgressHUD.dismiss()
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

  
}




extension AddBankCardVC{
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        

        
        return 1
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        
            return 4

        
    }
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        

            
        let tempCell : BankInfoCollectionCell =  tableView.dequeueReusableCell(withIdentifier: BankInfoCollectionCell.identifer()) as! BankInfoCollectionCell
        
        tempCell.model = model
        
        tempCell.index = indexPath
            
        
        return tempCell
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        

            
            return 46
     
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        
        return 36
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        
        if indexPath.row == 2 {
            view.endEditing(true)
            
            let temp = AllBankCarListVC()
            
            temp.block = {(name,code) -> () in
            
                self.model.bank_name = name
                
                self.model.bank_code = code
                
                self.tableView.reloadData()
            
            }
            
            navigationController?.pushViewController(temp, animated: true)
        }
        
    }
    
    
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        
 
        
        let temp = tableView.dequeueReusableHeaderFooterView(withIdentifier: OrderSureSetionView.identifer()) as! OrderSureSetionView
        
        if section == 0 {
            
            temp.section = 199
            
        }
        
        return temp
        
        
        
    }
    
    
    
    
}





extension AddBankCardVC : OrderBottomViewDeleage{
    
    
    func orderBottomViewBtnDidTap(){
        
        view.endEditing(true)
        
        
        if model.true_name == nil {
            
            alert(str: "请填写持卡人姓名")
            return
        }else{
            if model.true_name!.characters.count < 1 {
                
                alert(str: "请填写持卡人姓名")
                
            }
        }
        
        
        if model.bank_number == nil {
            alert(str: "请填写银行卡号")
            return
        }
        
        if isBankNumber() == false{
            alert(str: "银行卡号格式不正确")
            return
            
        }
        
        
        
        
        if model.bank_name == nil {
            
            alert(str: "请选择银行卡类型")
            return
        }else{
            if model.bank_name!.characters.count < 1 {
                
                alert(str: "请选择银行卡类型")
                
            }
        }

        
        
        
        if model.mob_phone == nil {
            alert(str: "请填写手机号")
            return
        }
        
        if isPhoneNumber() == false{
            alert(str: "手机号格式不正确")
            return
            
        }
        
        


        makeSurePay()
        
        QL1("点击了")
    }
    
    
    
  
    
    
    func makeSurePay() {
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["true_name"] = model.true_name as AnyObject
        
        parmeter["bank_code"] = model.bank_code as AnyObject

        parmeter["bank_name"] = model.bank_name as AnyObject

        parmeter["card_no"] = model.bank_number as AnyObject

        parmeter["mob_phone"] = model.mob_phone as AnyObject
        


        SVProgressHUD.show(withStatus: "正在添加...")
        
        NetworkTools.shared.sendRequest(method: .POST_METHOD, pathStr: "mobile/index.php?c=member_bank_card&a=card_add", parameters: parmeter) { [weak self] (responseObject, error) in
            
            
            
            if error == nil {
                
                SVProgressHUD.dismiss()
                

                if self?.block != nil{
                
                    self?.block!()

                }
                
                
               self?.navigationController?.popViewController(animated: true)
                
            }else{
                
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
            
        }
        
        
        
        
    }


    
    
    
    func isPhoneNumber() -> Bool {
        
        if model.mob_phone!.characters.count < 1 {
            return false
        }
        
        if model.mob_phone!.characters.count != 11 {
            return false
        }
        
        //电话号码
        let pattern = "[1][0-9]{10}"
        
        //caseInsensitive  忽略大小写  最常用
        //dotMatchesLineSeparators 允许 . 匹配任意字符，包括回车换行
        let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
        
        
        //根据规则匹配指定字符串中第一个符合规则的字符串，并且返回一个NSTextCheckingResult
        let res = regex.firstMatch(in: model.mob_phone!, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range:  NSRange(location: 0, length: model.mob_phone!.characters.count))
        
        
        if res?.range != nil {
            return true
            
        }else{
            
            return false
            
        }
        
        
        
    }
    
    
    
    
    func isBankNumber() -> Bool {
        
        QL1(model.bank_number)
        
        if model.bank_number!.characters.count < 1 {
            return false
        }
        
        if model.bank_number!.characters.count > 21 || model.bank_number!.characters.count < 16 {
            return false
        }
        
        let start = model.bank_number!.index(model.bank_number!.startIndex, offsetBy: 1)
        
        let tempStr = model.bank_number?.substring(to: start)
        
        if tempStr == "0" {
            
            return false

        }
        

        
  
        
    
        let pattern = "[1-9][0-9]{15,20}"
        
        //caseInsensitive  忽略大小写  最常用
        //dotMatchesLineSeparators 允许 . 匹配任意字符，包括回车换行
        let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
        
        
        //根据规则匹配指定字符串中第一个符合规则的字符串，并且返回一个NSTextCheckingResult
        let res = regex.firstMatch(in: model.bank_number!, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range:  NSRange(location: 0, length: model.bank_number!.characters.count))
        
        
        if res?.range != nil {
            
            QL1(res?.range.location)
            QL1(res?.range.length)
            return true
            
        }else{
            
            return false
            
        }
        
        
        
    }
    
    
    
    
    
    
    func alert(str : String) {
        
        let tempVC = UIAlertController(title: nil, message: str, preferredStyle: .alert)
        
        let action1 = UIAlertAction(title: "确定", style: .destructive) { (action) in
            
        }
        
        
        
        let action2 = UIAlertAction(title: "取消", style: .default) { (action) in
            
            
        }
        
        tempVC.addAction(action2)
        tempVC.addAction(action1)
        
        present(tempVC, animated: true, completion: nil)
        
        
    }



}
